package com.mflex.mwms.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.google.gson.reflect.TypeToken;
import com.mflex.mwms.R;
import com.mflex.mwms.adapter.TeslaCompareDetailAdapter;
import com.mflex.mwms.model.CustomApiResult;
import com.mflex.mwms.model.Task;
import com.mflex.mwms.model.TaskDetail;
import com.mflex.mwms.model.TeslaComapreInfo;
import com.mflex.mwms.model.TeslaCustomCompareRequest;
import com.mflex.mwms.model.enumeration.CustomCompare;
import com.mflex.mwms.utils.MessageUtils;
import com.mflex.mwms.utils.XToastUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.CallBackProxy;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class CatlXiDianCompareDetailActivity extends BaseActivity {
    @BindView(R.id.stv_TaskNo)
    EditText stvTaskNo;
    @BindView(R.id.stv_CustomPallet)
    EditText stvCustomPallet;
    @BindView(R.id.stv_BoxNumber)
    EditText stvBoxNumber;
    @BindView(R.id.stv_CustomBoxNumber)
    EditText stvCustomBoxNumber;
    @BindView(R.id.button_clear)
    Button buttonClear;

    @BindView(R.id.button_submit)
    Button buttonSubmit;

    @BindView(R.id.lvTaskList)
    ListView lvTaskList;

    MiniLoadingDialog mMiniLoadingDialog;

    private Task task;

    private String customPNPallet;
    private String customPNBox;
    private int qty;

    private int scanQty;

    List<TeslaComapreInfo> teslaComapreInfoList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_catl_xi_dian_compare_detail);
        ButterKnife.bind(this);
        mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this, "加载...");


        stvCustomPallet.setOnKeyListener(this);
        stvBoxNumber.setOnKeyListener(this);
        stvCustomBoxNumber.setOnKeyListener(this);
        buttonClear.setOnClickListener(this);
        buttonSubmit.setOnClickListener(this);

        teslaComapreInfoList = new ArrayList<>();

        stvCustomPallet.postDelayed(new Runnable() {
            @Override
            public void run() {
                stvCustomPallet.requestFocus();
            }
        }, 200);

        Intent intent = getIntent();
        Type listType = new TypeToken<Task>() {
        }.getType();
        task = (Task) JsonUtil.fromJson(intent.getStringExtra("task"), listType);

        stvTaskNo.setText(task.getTaskNo());

        for (TaskDetail taskDetail : task.getTaskDetails()) {
            TeslaComapreInfo teslaComapreInfo = new TeslaComapreInfo();
            teslaComapreInfo.setMark(String.valueOf(CustomCompare.CATLXIDIAN.getCode()));
            teslaComapreInfo.setBoxNumber(taskDetail.getDetailName());
            teslaComapreInfo.setPn(taskDetail.getPN());
            teslaComapreInfo.setTaskNo(task.getTaskNo());
            teslaComapreInfoList.add(teslaComapreInfo);
        }

        TeslaCompareDetailAdapter teslaCompareDetailAdapter = new TeslaCompareDetailAdapter(CatlXiDianCompareDetailActivity.this, teslaComapreInfoList);
        lvTaskList.setAdapter(teslaCompareDetailAdapter);

        qty = 0;
        scanQty = 0;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_clear:
                clearButtonMd(view);
                break;
            case R.id.button_submit:
                SubmitButtonMd(view);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && (i == 66 || i == 61)) {
            switch (view.getId()) {
                case R.id.stv_CustomPallet:
                    checkCustomPallet(view);
                    break;
                case R.id.stv_BoxNumber:
                    checkBoxNumber(view);
                    break;
                case R.id.stv_CustomBoxNumber:
                    checkCustomBoxNumber(view);
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    private void checkCustomPallet(View view) {
        if (StringUtils.isEmpty(stvCustomPallet.getText().toString())) {
            stvCustomPallet.setText("");
            stvCustomPallet.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvCustomPallet.requestFocus();
                }
            }, 200);
            return;
        }

        String[] customPalletNoList = stvCustomPallet.getText().toString().split("@");
        if (customPalletNoList.length != 9) {
//            XToastUtils.error("客户栈板标格式不正确1", 3000);
            MessageUtils.errorMsgAndVoice(CatlXiDianCompareDetailActivity.this, "客户栈板标格式不正确");
            stvCustomPallet.setText("");
            stvCustomPallet.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvCustomPallet.requestFocus();
                }
            }, 200);
            return;
        }
        customPNPallet = customPalletNoList[4];


        if (!StringUtils.isInteger(customPalletNoList[6])) {
//            XToastUtils.error("客户栈板标格式不正确5", 3000);
            MessageUtils.errorMsgAndVoice(CatlXiDianCompareDetailActivity.this, "客户栈板标格式不正确");
            stvCustomPallet.setText("");
            stvCustomPallet.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvCustomBoxNumber.requestFocus();
                }
            }, 200);
            return;
        }
        qty = Integer.parseInt(customPalletNoList[7]);

        if (!StringUtils.equals(task.getStockoutDetails().get(0).getCOPN(),customPNPallet)) {
//            XToastUtils.error("栈板标与COPN不匹配", 3000);
            MessageUtils.errorMsgAndVoice(CatlXiDianCompareDetailActivity.this, "栈板标与COPN不匹配");
            stvCustomPallet.setText("");
            stvCustomPallet.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvCustomPallet.requestFocus();
                }
            }, 200);
            return;
        }
        stvCustomPallet.setFocusable(false);
        stvCustomBoxNumber.postDelayed(new Runnable() {
            @Override
            public void run() {
                stvCustomBoxNumber.requestFocus();
            }
        },200);
    }

    private void checkBoxNumber(View view) {
        if (StringUtils.isEmpty(stvCustomPallet.getText().toString())) {
            stvCustomBoxNumber.setText("");
            stvBoxNumber.setText("");
            stvCustomBoxNumber.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvCustomBoxNumber.requestFocus();
                }
            },200);
            return;
        }
        boolean flag = false;

        for (TeslaComapreInfo teslaComapreInfo : teslaComapreInfoList) {
            if (StringUtils.equals(teslaComapreInfo.getBoxNumber(), stvBoxNumber.getText().toString())) {
                flag = true;
                break;
            }
        }
        if (!flag) {
//            XToastUtils.error("该箱不在任务列表中", 3000);
            MessageUtils.errorMsgAndVoice(CatlXiDianCompareDetailActivity.this, "该箱不在任务列表中");
            stvBoxNumber.setText("");
            stvBoxNumber.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvBoxNumber.requestFocus();
                }
            }, 200);
            return;
        }
        boolean flag2 = false;

        for (TeslaComapreInfo teslaComapreInfo : teslaComapreInfoList) {
            if (StringUtils.equals(teslaComapreInfo.getBoxNumber(), stvBoxNumber.getText().toString()) && teslaComapreInfo.checked) {
                flag2 = true;
                break;
            }
        }
        if (flag2) {
//            XToastUtils.error("该箱已扫描", 3000);
            MessageUtils.errorMsgAndVoice(CatlXiDianCompareDetailActivity.this, "该箱已扫描");
            stvBoxNumber.setText("");
            stvBoxNumber.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvBoxNumber.requestFocus();
                }
            }, 200);
            return;
        }

        TaskDetail taskDetailSel = new TaskDetail();
        for (TaskDetail taskDetail : task.getTaskDetails()) {
            if (StringUtils.equals(taskDetail.getDetailName(), stvBoxNumber.getText().toString())) {
                taskDetailSel = taskDetail;
                break;
            }
        }

        //比较数量
        scanQty = scanQty + Integer.parseInt(taskDetailSel.getQty());


        if (scanQty == qty) {
            for (TeslaComapreInfo teslaComapreInfo : teslaComapreInfoList) {
                if (StringUtils.equals(teslaComapreInfo.getBoxNumber(), stvBoxNumber.getText().toString())) {
                    teslaComapreInfo.setCustomPallet(stvCustomPallet.getText().toString());
                    teslaComapreInfo.setCustomBoxNumber(stvCustomBoxNumber.getText().toString());
                    teslaComapreInfo.setDeveliverNo(task.getDeliverGoodsNo());
                    teslaComapreInfo.setTaskNo(task.getTaskNo());
                    teslaComapreInfo.setMark(String.valueOf(CustomCompare.CATLXIDIAN.getCode()));
                    teslaComapreInfo.setChecked(true);
                }
            }

            stvCustomPallet.setFocusable(true);
            stvCustomPallet.setFocusableInTouchMode(true);
            qty = 0;
            scanQty = 0;
            customPNPallet = "";
            stvCustomPallet.setText("");
            stvCustomBoxNumber.setText("");
            stvBoxNumber.setText("");
            stvCustomPallet.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvCustomPallet.requestFocus();
                }
            },200);

        } else if (scanQty < qty) {
            for (TeslaComapreInfo teslaComapreInfo : teslaComapreInfoList) {
                if (StringUtils.equals(teslaComapreInfo.getBoxNumber(), stvBoxNumber.getText().toString())) {
                    teslaComapreInfo.setCustomPallet(stvCustomPallet.getText().toString());
                    teslaComapreInfo.setCustomBoxNumber(stvCustomBoxNumber.getText().toString());
                    teslaComapreInfo.setDeveliverNo(task.getDeliverGoodsNo());
                    teslaComapreInfo.setTaskNo(task.getTaskNo());
                    teslaComapreInfo.setMark(String.valueOf(CustomCompare.CATLXIDIAN.getCode()));
                    teslaComapreInfo.setChecked(true);
                }
            }

            stvBoxNumber.setText("");
            stvCustomBoxNumber.setText("");
            stvCustomBoxNumber.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvCustomBoxNumber.requestFocus();
                }
            }, 200);
        } else {
            scanQty = scanQty - Integer.parseInt(taskDetailSel.getQty());
//            XToastUtils.error("超出栈板的数量", 3000);
            MessageUtils.errorMsgAndVoice(CatlXiDianCompareDetailActivity.this, "超出栈板的数量");
            stvBoxNumber.setText("");
            stvCustomBoxNumber.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvCustomBoxNumber.requestFocus();
                }
            },200);
        }
        Collections.sort(teslaComapreInfoList, new Comparator<TeslaComapreInfo>() {
            @Override
            public int compare(TeslaComapreInfo t0, TeslaComapreInfo t1) {
                if(!t0.isChecked()&&t1.isChecked()){
                    return -1;
                }
                return 0;
            }
        });
        TeslaCompareDetailAdapter teslaCompareDetailAdapter = new TeslaCompareDetailAdapter(CatlXiDianCompareDetailActivity.this, teslaComapreInfoList);
        lvTaskList.setAdapter(teslaCompareDetailAdapter);
    }

    private void checkCustomBoxNumber(View view) {
        if (StringUtils.isEmpty(stvCustomBoxNumber.getText().toString())) {
            return;
        }
        String[] customBoxList = stvCustomBoxNumber.getText().toString().split("@");
        if (customBoxList.length != 10) {
//            XToastUtils.error("客户箱标格式不正确", 3000);
            MessageUtils.errorMsgAndVoice(CatlXiDianCompareDetailActivity.this, "客户箱标格式不正确");
            stvCustomPallet.setText("");
            stvCustomPallet.requestFocus();
            return;
        }
        customPNBox = customBoxList[4];
        if (!StringUtils.equals(task.getTaskDetails().get(0).getCOPN(),customPNBox)) {
//            XToastUtils.error("客户箱标与COPN不匹配", 3000);
            MessageUtils.errorMsgAndVoice(CatlXiDianCompareDetailActivity.this, "客户箱标与COPN不匹配");
            stvCustomBoxNumber.setText("");
            stvCustomBoxNumber.requestFocus();

        }
        boolean flag = false;
        for (TeslaComapreInfo teslaComapreInfo : teslaComapreInfoList) {
            if(StringUtils.equals(stvCustomBoxNumber.getText().toString(),teslaComapreInfo.getCustomBoxNumber())){
                flag = true;
                break;
            }
        }
        if(flag){
            MessageUtils.errorMsgAndVoice(CatlXiDianCompareDetailActivity.this, "客户箱标已在列表中");
            stvCustomBoxNumber.setText("");

            stvCustomBoxNumber.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvCustomBoxNumber.requestFocus();
                }
            },200);
        }
    }
    private void clearButtonMd(View v) {
        stvCustomPallet.setFocusable(true);
        stvCustomPallet.setFocusableInTouchMode(true);
        qty = 0;
        scanQty = 0;
        customPNPallet = "";
        stvCustomPallet.setText("");
        stvCustomPallet.requestFocus();
        stvCustomBoxNumber.setText("");
        stvBoxNumber.setText("");
        teslaComapreInfoList = new ArrayList<>();
        for (TaskDetail taskDetail : task.getTaskDetails()) {
            TeslaComapreInfo teslaComapreInfo = new TeslaComapreInfo();
            teslaComapreInfo.setMark(String.valueOf(CustomCompare.CATLXIDIAN.getCode()));
            teslaComapreInfo.setBoxNumber(taskDetail.getDetailName());
            teslaComapreInfo.setPn(taskDetail.getPN());
            teslaComapreInfo.setTaskNo(task.getTaskNo());
            teslaComapreInfoList.add(teslaComapreInfo);
        }
        TeslaCompareDetailAdapter teslaCompareDetailAdapter = new TeslaCompareDetailAdapter(CatlXiDianCompareDetailActivity.this, teslaComapreInfoList);
        lvTaskList.setAdapter(teslaCompareDetailAdapter);
        XToastUtils.success("重置成功！");
    }

    private void SubmitButtonMd(View view) {
        boolean flag = false;
        for(TeslaComapreInfo teslaComapreInfo : teslaComapreInfoList){
            if(!teslaComapreInfo.isChecked()){
                flag = true;
            }
        }
        if(flag){
//            XToastUtils.error("没有比对完成！",3000);
            MessageUtils.errorMsgAndVoice(CatlXiDianCompareDetailActivity.this, "没有比对完成");
            return;
        }

        TeslaCustomCompareRequest request = new TeslaCustomCompareRequest();
        request.setTeslaCustomCompares(teslaComapreInfoList);
        mMiniLoadingDialog.show();
        XHttp.post("api/Comparison/CustomLabelCompare")
                .upJson(JsonUtil.toJson(request))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {

                    @Override
                    public void onSuccess(String response) {
                        mMiniLoadingDialog.dismiss();
                        XToastUtils.success("比对成功", 2500);

                        setResult(0);
                        finish();
                    }

                    @Override
                    public void onError(ApiException e) {
                        mMiniLoadingDialog.dismiss();
                        MessageUtils.errorMsgAndVoice(CatlXiDianCompareDetailActivity.this, e);
                    }
                }) {
                });
    }
}